import { login, getUserInfo, logout } from '../../api/user'
import { setItem,  getItem } from '../../utils/storage'
import { TOKEN, USERINFO, SCHOOLID } from '../../constant/index'
import router, {resetRouter} from '../../router/index'
import { Message } from 'element-ui'

export default {
    namespaced: true,
    state: ()=> ({
        token: getItem(TOKEN) || '',
        userInfo: getItem(USERINFO) || '',
        schoolId: getItem(SCHOOLID) || '',
    }),
    mutations: {
        setToken(state, token){
            state.token = token;
            setItem(TOKEN, token)
        },
        setUserInfo(state, userInfo){
            state.userInfo = userInfo
        },
        setSchoolId(state, schoolId){
            state.schoolId = schoolId
            setItem(SCHOOLID, schoolId)
        }
    },
    actions: {
        login({commit}, loginForm){
            // let { username, password } = loginForm
            return new Promise(async (resolve, reject) => {
                let res = await login(loginForm);
                // console.log(res.token);
                commit('setToken', res.token)
                router.push('/')
                resolve(res)
            })
        },
        userInfo({commit}){
            return new Promise(async (resolve, reject) => {
                let res = await getUserInfo();
                commit('setUserInfo', res)
                resolve(res)
            })
        },
        schoolId({commit}, id){
            commit('setSchoolId', id)
        },
        async logout({commit}){
            await logout();
            commit('setToken', null)
            commit('setUserInfo', null)
            commit('setSchoolId', null)
            router.push('/login');
            resetRouter();
            Message.success('退出成功')
        }
    }
}